<?php defined('SYSPATH') or die('No direct script access.');

/**
 * @example 三种情况
 *
 */
class Model_Log extends Model_Database {
	
	public static $pause = FALSE;

	public static function log($extra_data = array())
	{
		if (self::$pause) return 0;

		$uid = Auth::instance()->get_user();
		$request = Request::initial();

		$client_ip = 0;
		$request_data = 'minion';
		if (!empty($request))
		{
			$request_data = array('url' => $request->url(TRUE), 'protocol' => $request->protocol(), 'cookie' => $request->cookie(), 'post' => $request->post(), 'referrer' => $request->referrer(), 'method' => $request->method(), 'user_agent' => $request::$user_agent, 'accept_lang' => $request->accept_lang(), 'accept_encoding' => $request->accept_encoding(), 'accept_type' => $request->accept_type(), 'requested_with' => $request->requested_with(), 'secure' => $request->secure());
			$client_ip = ip2long($request::$client_ip);
		}
		$t = self::get_debug();
		$operation = $t['operation'];
		$_data = array_merge($t['data'],$extra_data); //以$extra_data为基准

		$query = DB::insert('log',array('uid','ip', 'request','timeline','operation','data'))->values(array($uid,$client_ip,serialize($request_data),time(),$operation,serialize($_data)))->execute();
		return array_shift($query);
	}

	public static function get_string($user, int $ip, int $timeline, string $operation, array $data)
	{
		$msg = Kohana::message('log','templates.'.$operation);

		if(is_int($user))
			$user = Model::instance('member')->get($user);
		

		$_data = array(':o_username' => !empty($user['username']) ? $user['username'] : 'Guest',':o_uid' => intval($user['uid']),':o_client_ip' => long2ip($ip),':o_timeline' => $timeline, ':o_datetime' => date('Y-m-d H:i:s',$timeline));
		$_data += array_hashmap($data,'/',':'); //将数组的key转化为:a/b/c

		$prefix = '[:o_datetime] :o_username(UID::o_uid, IP::o_client_ip) ';

		$msg = $prefix . $msg;

		return __($msg, $_data);
	}

	private static function get_debug()
	{
		$debug = array();
		if (version_compare(PHP_VERSION, '5.4.0', '>=') )
			$debug = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT,  3);
		else
			$debug = debug_backtrace();

		if (!isset($debug[2]))
			return FALSE;

		$_class = $debug[2]; unset($debug);
		$defined_vars = $_class['args'];
		$operation = strtolower(str_replace(array('Model_','Controller_','View_'),'', $_class['class']).'/'.$_class['function']);
		$class = new ReflectionClass($_class['class']);
		$function = $class->getMethod($_class['function']); //ReflectionMethod 
		$parameters = $function->getParameters(); //ReflectionParameter 
		unset($_class);
		$_data = array();
		$count = count($parameters);
		for ($i=0; $i < $count; $i++)
		{ 
			$key = $parameters[$i]->getName();
			$default = $parameters[$i]->isDefaultValueAvailable() ? $parameters[$i]->getDefaultValue() : NULL;
			$_data[$key] = isset($defined_vars[$i]) ? $defined_vars[$i] : $default;
		}

		return array('operation' => $operation, 'data' => $_data);
	}

	public static function get_last($uid = 0, $operation = '')
	{
		$uid = !empty($uid) ? $uid : Auth::instance()->get_user();
		if (empty($operation))
		{
			$t = self::get_debug();
			$operation = $t['operation'];
		}

		$query = DB::select('*')->from('log')->where('uid','=',$uid)->order_by('timeline','DESC')->limit(1);
		if ($operation != '*')
			$query->and_where('operation','=',$operation);
		
		return $query->execute()->current();
	}

	public static function get_list($uid = 0, $operation = '', $page = 1, $pagesize = 0)
	{
		$uid = !empty($uid) ? $uid : Auth::instance()->get_user();
		if (empty($operation))
		{
			$t = self::get_debug();
			$operation = $t['operation'];
		}
		$data = array();$count = 0;
		$query = DB::select()->from('log')->where('uid','=',$uid)->order_by('timeline','DESC');
		if ($operation != '*')
			$query->and_where('operation','=',$operation);
		
		return $this->make_page($query,'*','lid','lid',$page,$pagesize);
	}

}